<template>
  <div class="upload-item-box">
    <div class="upload-item">
      <!-- capture="camera"  -->
      <!--:src="uploadImgObj.attachImgSrc"-->
      <!-- uploadImgObj.attachImgSrc 上传图片; uploadImgObj.attachDemoImgSrc 示例图片 -->
      <span v-if="uploadBtnTitle" class="c-409eff">{{uploadBtnTitle}}</span>
      <img v-if="uploadImgObj.attachImgSrc" class="ximg" :src="uploadImgObj.attachImgSrc"  alt="">
      <img v-else class="ximg" :src="uploadImgObj.attachDemoImgSrc"  alt="">
      <input v-if="isUploadFile"  class="upload-item-input" :class="uploadImgObj.key" type="file" accept="image/*" name="file" :data-img="uploadImgObj.key" @change="PreviewImage" />
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import * as ImgCompress from '@/utils/canvas/compress'
  import * as Watermark from '@/utils/canvas/watermark'
  import * as Utils from '@/utils/index'
  import axios from 'axios'
  export default {
    name: 'uploadImg',
    props: ['uploadImgObj', 'uploadPostData', 'uploadBtnTitle', 'uploadWatermarkData'],
    /**
     * uploadImgObj 必传  附件相关数据
     * uploadPostData 必传  七牛上传请求参数（七牛token/七牛host）
     * uploadBtnTitle 非必传  按钮标题
     * uploadWatermarkData 非必传  水印数据（有则执行水印，无则不执行水印打印）
     **/
    data() {
      return {
        isUploadFile: true // 控制销毁 上传
      }
    },
    created() {
      console.log('uploadImg-$props.uploadImgObj', this.$props.uploadImgObj)
    },
    mounted() {
    },
    methods: {
      unpload: function(compress_obj, imgName, imgBase) {
        // console.log('compress_obj', compress_obj)
        const that = this
        const res_imgName = imgName
        const res_compress_obj = compress_obj
        const res_img_base64 = imgBase
        let res_data = {
          file: '',
          hash: '',
          imgPath: '',
          imgName: '',
          uploadImgObj: {}
        }
        this.isUploadFile = true
        const formData = new FormData()
        formData.append('file', res_compress_obj)
        formData.append('token', that.uploadPostData.token)
        axios({
          method: 'POST',
          url: that.uploadPostData.imageUrl,
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          console.log('图片上传()-res.data', res.data)
          res_data = {
            file: res_compress_obj,
            hash: res.data.hash,
            imgPath: res_img_base64,
            imgName: res_imgName,
            uploadImgObj: that.uploadImgObj
          }
          res_data.status = true // 代表上传成功
          that.$emit('upload-img-end', res_data)
        }).catch(res => {
          console.log('res', res)
          res_data.status = false // 代表上传失败
          that.$emit('upload-img-end', res_data)
        })
      },
      // 压缩判断
      PreviewImage: function(e) {
        const that = this
        that.isUploadFile = false // 销毁 input 以达到 清除 input value 的值目的,然后达到 能重复上传 同一个文件名 文件的目的
        this.$emit('change-loading-val')
        console.log('e', e, 'file', e.target.files[0])
        const newFile = e.target.files[0]
        const imgName = e.target.files[0].name
        const check_file = that.beforeAvatarUpload(newFile)
        let imgBase = ''
        if (check_file) {
          that.$emit('upload-img-start') // 上传开始 开启loading
          const reader = new FileReader()
          // props 父组件是否有传 水印数据 , Utils.isLegalObject() 判断合法对象
          const isHaveWatermarkData = Utils.isLegalObject(that.$props.uploadWatermarkData)
          let watermarkData = null
          if (isHaveWatermarkData) { watermarkData = that.$props.uploadWatermarkData }
          if (newFile.size / 1024 / 1024 > 5) {
            console.log('压缩')
            ImgCompress.photoCompress(newFile, { quality: 0.8 }, function(base64Codes) {
              const blob = ImgCompress.convertBase64UrlToBlob(base64Codes)
              const { lastModified, type } = newFile
              const compress_file = new File([blob], imgName, { type: type, lastModified: lastModified })
              imgBase = base64Codes
              if (isHaveWatermarkData) {
                console.log('加水印')
                Watermark.addWatermark(compress_file, watermarkData, function(base64Codes) {
                  const blob = Utils.convertBase64UrlToBlob(base64Codes)
                  const { lastModified, type } = newFile
                  const watermark_file = new File([blob], imgName, { type: type, lastModified: lastModified })
                  that.unpload(watermark_file, imgName, imgBase)
                  that.isUploadFile = true
                })
              } else {
                console.log('未加水印')
                that.unpload(compress_file, imgName, imgBase)
                that.isUploadFile = true
              }
            })
          } else {
            // console.log('不压缩的', newFile)
            if (isHaveWatermarkData) {
              console.log('加水印')
              Watermark.addWatermark(newFile, watermarkData, function(base64Codes) {
                const blob = Utils.convertBase64UrlToBlob(base64Codes)
                const { lastModified, type } = newFile
                const watermark_file = new File([blob], imgName, { type: type, lastModified: lastModified })
                imgBase = base64Codes
                that.unpload(watermark_file, imgName, imgBase)
                that.isUploadFile = true
              })
            } else {
              console.log('未加水印')
              reader.readAsDataURL(newFile) // 调用reader.readAsDataURL()方法，把图片转成base64
              reader.addEventListener('load', res => {
                imgBase = res.srcElement.result
                that.unpload(newFile, imgName, imgBase)
                that.isUploadFile = true
              }, false)
            }
          }
        }
      },
      beforeAvatarUpload(file) {
        if (!(file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg')) {
          this.$message({
            message: '请上传 jpg/jpeg/png 格式的图片!',
            type: 'warning',
            duration: 3000
          })
          return
        }
        // const isLt2M = file.size / 1024 / 1024 < 5
        // if (!isLt2M) {
        // this.$message({
        //   message: '图片大小不能超过 5MB!',
        //   type: 'warning',
        //   duration: 2000
        // })
        //   return
        // }
        return true
      }
    }
  }
</script>

<style scoped>
  .upload-item{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    background-size: 120%;
    position: relative;
    overflow: hidden;
    border: none;
    /*border: 1px solid #dae7f6;*/
    /*background-color: #f5f5f5;*/
  }
  .upload-item:hover{
    border: none;
    /*border: 1px solid #1e90ff;*/
  }
  .ximg {
    width: 100%;
    height: 100%;
    display: block;
  }
  .upload-item-input{
    opacity: 0;
    width: 100%;
    height: 100%;
    background-size: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
</style>
